import { createBrowserRouter } from "react-router-dom";
import UserLayout from "../layouts/UserLayout.tsx";
import AdminLayout from "../layouts/AdminLayout.tsx";

// User views
import Home from "../views/user/Home.tsx";
import ProductList from "../views/user/ProductList.tsx";
import ProductDetail from "../views/user/ProductDetail.tsx";
import Customization from "../views/user/Customization.tsx";
import Cart from "../views/user/Cart.tsx";
import UserProfile from "../views/user/Profile.tsx";
import About from "../views/user/About.tsx";

// Admin views
import AdminDashboard from "../views/admin/Dashboard.tsx";
import ProductManagement from "../views/admin/ProductManagement.tsx";
import OrderManagement from "../views/admin/OrderManagement.tsx";
import OrderStatistics from "../views/admin/OrderStatistics.tsx";

// 为路由添加元数据类型定义
interface RouteMeta {
  title: string;
  description: string;
  keywords: string;
}

interface RouteConfig {
  path: string;
  element: React.ReactNode;
  meta?: RouteMeta;
  children?: RouteConfig[];
}

const routes: RouteConfig[] = [
  {
    path: "/",
    element: <UserLayout />,
    meta: {
      title: "家具商城 - 首页",
      description: "欢迎来到家具商城，为您提供高品质家具定制服务",
      keywords: "家具商城, 家具定制, 家具购买, 家具设计"
    },
    children: [
      {
        path: "",
        element: <Home />,
        meta: {
          title: "家具商城 - 首页",
          description: "欢迎来到家具商城，为您提供高品质家具定制服务",
          keywords: "家具商城, 家具定制, 家具购买, 家具设计"
        },
      },
    ],
  },
  {
    path: "/user",
    element: <UserLayout />,
    meta: {
      title: "家具商城 - 用户中心",
      description: "家具商城用户中心，提供商品浏览、定制、购物车等服务",
      keywords: "家具商城, 用户中心, 商品浏览, 家具定制, 购物车"
    },
    children: [
      {
        path: "",
        element: <Home />,
        meta: {
          title: "家具商城 - 首页",
          description: "欢迎来到家具商城，为您提供高品质家具定制服务",
          keywords: "家具商城, 家具定制, 家具购买, 家具设计"
        },
      },
      {
        path: "products",
        element: <ProductList />,
        meta: {
          title: "家具商城 - 商品列表",
          description: "浏览我们的家具产品，选择您喜欢的商品进行定制",
          keywords: "家具商城, 商品列表, 家具产品, 家具定制"
        },
      },
      {
        path: "products/:id",
        element: <ProductDetail />,
        meta: {
          title: "家具商城 - 商品详情",
          description: "查看家具商品详细信息，了解产品特点和定制选项",
          keywords: "家具商城, 商品详情, 家具产品, 产品特点"
        },
      },
      {
        path: "customization/:id",
        element: <Customization />,
        meta: {
          title: "家具商城 - 定制商品",
          description: "在线定制您的家具，选择颜色、材质和尺寸",
          keywords: "家具商城, 家具定制, 颜色选择, 材质选择, 尺寸选择"
        },
      },
      {
        path: "cart",
        element: <Cart />,
        meta: {
          title: "家具商城 - 购物车",
          description: "查看和管理您的购物车，结算您选择的商品",
          keywords: "家具商城, 购物车, 商品结算, 订单管理"
        },
      },
      {
        path: "profile",
        element: <UserProfile />,
        meta: {
          title: "家具商城 - 个人中心",
          description: "管理您的个人信息、订单和收藏",
          keywords: "家具商城, 个人中心, 个人信息, 订单管理, 收藏管理"
        },
      },
      {
        path: "about",
        element: <About />,
        meta: {
          title: "家具商城 - 关于我们",
          description: "了解家具商城的发展历程和团队介绍",
          keywords: "家具商城, 关于我们, 发展历程, 团队介绍"
        },
      },
    ],
  },
  {
    path: "/admin",
    element: <AdminLayout />,
    meta: {
      title: "家具商城 - 管理后台",
      description: "家具商城管理后台，管理商品、订单和统计数据",
      keywords: "家具商城, 管理后台, 商品管理, 订单管理, 数据统计"
    },
    children: [
      {
        path: "",
        element: <AdminDashboard />,
        meta: {
          title: "家具商城 - 管理仪表板",
          description: "查看商店运营数据和最新订单信息",
          keywords: "家具商城, 管理仪表板, 运营数据, 订单信息"
        },
      },
      {
        path: "products",
        element: <ProductManagement />,
        meta: {
          title: "家具商城 - 商品管理",
          description: "管理家具商品信息，包括添加、编辑和删除商品",
          keywords: "家具商城, 商品管理, 商品信息, 添加商品, 编辑商品"
        },
      },
      {
        path: "orders",
        element: <OrderManagement />,
        meta: {
          title: "家具商城 - 订单管理",
          description: "管理客户订单，处理发货和退款请求",
          keywords: "家具商城, 订单管理, 客户订单, 发货处理, 退款处理"
        },
      },
      {
        path: "statistics",
        element: <OrderStatistics />,
        meta: {
          title: "家具商城 - 统计报表",
          description: "查看销售统计数据和业务分析报告",
          keywords: "家具商城, 统计报表, 销售数据, 业务分析, 数据报告"
        },
      },
    ],
  },
];

const router = createBrowserRouter(routes);

/**
 * @description 监听路由变化，路由跳转时根据当前路由设置 title 和 meta 元数据到页面上，同时支持子路由的标题设置
 * @param {*}
 * @return {*}
 */
export const setTitle = (pathname: string) => {
  // 遍历所有路由查找匹配项
  for (const route of routes) {
    // 检查主路由是否匹配
    if (route.path === pathname) {
      // 设置标题
      if (route.meta?.title) {
        document.title = route.meta.title;
      }
      
      // 设置 meta 标签
      if (route.meta?.description) {
        let descriptionMeta = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
        if (!descriptionMeta) {
          descriptionMeta = document.createElement('meta') as HTMLMetaElement;
          descriptionMeta.name = 'description';
          document.head.appendChild(descriptionMeta);
        }
        descriptionMeta.content = route.meta.description;
      }
      
      if (route.meta?.keywords) {
        let keywordsMeta = document.querySelector('meta[name="keywords"]') as HTMLMetaElement | null;
        if (!keywordsMeta) {
          keywordsMeta = document.createElement('meta') as HTMLMetaElement;
          keywordsMeta.name = 'keywords';
          document.head.appendChild(keywordsMeta);
        }
        keywordsMeta.content = route.meta.keywords;
      }
      
      return;
    }
    
    // 检查子路由
    if (route.children) {
      for (const child of route.children) {
        // 构造完整的子路由路径
        const fullPath = route.path === "/" ? `/${child.path}` : `${route.path}/${child.path}`;
        
        // 特殊处理 /user 路径的情况
        const userPath = route.path === "/user" ? `/user/${child.path}` : fullPath;
        
        // 检查嵌套子路由
        if (child.children) {
          for (const grandChild of child.children) {
            const grandFullPath = `${fullPath}/${grandChild.path}`;
            const grandUserPath = `${userPath}/${grandChild.path}`;
            
            if (grandFullPath === pathname || grandUserPath === pathname) {
              // 设置标题
              if (grandChild.meta?.title) {
                document.title = grandChild.meta.title;
              } else if (child.meta?.title) {
                document.title = child.meta.title;
              } else if (route.meta?.title) {
                document.title = route.meta.title;
              }
              
              // 设置 meta 标签
              const meta = grandChild.meta || child.meta || route.meta;
              if (meta?.description) {
                let descriptionMeta = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
                if (!descriptionMeta) {
                  descriptionMeta = document.createElement('meta') as HTMLMetaElement;
                  descriptionMeta.name = 'description';
                  document.head.appendChild(descriptionMeta);
                }
                descriptionMeta.content = meta.description;
              }
              
              if (meta?.keywords) {
                let keywordsMeta = document.querySelector('meta[name="keywords"]') as HTMLMetaElement | null;
                if (!keywordsMeta) {
                  keywordsMeta = document.createElement('meta') as HTMLMetaElement;
                  keywordsMeta.name = 'keywords';
                  document.head.appendChild(keywordsMeta);
                }
                keywordsMeta.content = meta.keywords;
              }
              
              return;
            }
          }
        }
        
        if (userPath === pathname || fullPath === pathname) {
          // 设置标题
          if (child.meta?.title) {
            document.title = child.meta.title;
          } else if (route.meta?.title) {
            document.title = route.meta.title;
          }
          
          // 设置 meta 标签
          const meta = child.meta || route.meta;
          if (meta?.description) {
            let descriptionMeta = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
            if (!descriptionMeta) {
              descriptionMeta = document.createElement('meta') as HTMLMetaElement;
              descriptionMeta.name = 'description';
              document.head.appendChild(descriptionMeta);
            }
            descriptionMeta.content = meta.description;
          }
          
          if (meta?.keywords) {
            let keywordsMeta = document.querySelector('meta[name="keywords"]') as HTMLMetaElement | null;
            if (!keywordsMeta) {
              keywordsMeta = document.createElement('meta') as HTMLMetaElement;
              keywordsMeta.name = 'keywords';
              document.head.appendChild(keywordsMeta);
            }
            keywordsMeta.content = meta.keywords;
          }
          
          return;
        }
      }
    }
  }
  
  // 默认标题和meta信息
  document.title = "家具商城";
  let descriptionMeta = document.querySelector('meta[name="description"]') as HTMLMetaElement | null;
  if (!descriptionMeta) {
    descriptionMeta = document.createElement('meta') as HTMLMetaElement;
    descriptionMeta.name = 'description';
    document.head.appendChild(descriptionMeta);
  }
  descriptionMeta.content = "家具商城 - 提供高品质家具定制服务";
  
  let keywordsMeta = document.querySelector('meta[name="keywords"]') as HTMLMetaElement | null;
  if (!keywordsMeta) {
    keywordsMeta = document.createElement('meta') as HTMLMetaElement;
    keywordsMeta.name = 'keywords';
    document.head.appendChild(keywordsMeta);
  }
  keywordsMeta.content = "家具商城, 家具定制, 家具购买, 家具设计";
}

export default router;